import config from '../config/config';

export const request = (options) => {
  const token = wx.getStorageSync('token');
  
  if (!token && !options.url.includes('/user/login')) {
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      wx.reLaunch({
        url: '/pages/index/index'
      });
    }, 1500);
    return Promise.reject(new Error('请先登录'));
  }

  const url = `${config.BASE_API}/api${options.url}`;
  
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'content-type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        try {
          console.log('API响应原始数据：', res.data);

          let responseData = res.data;
          if (typeof responseData === 'string') {
            try {
              responseData = JSON.parse(responseData.trim());
            } catch (parseErr) {
              console.error('JSON解析失败：', parseErr);
              throw new Error('数据格式错误');
            }
          }

          if (res.statusCode === 200) {
            if (responseData.code === 0) {
              if (Array.isArray(responseData.data)) {
                resolve(responseData.data.map(item => {
                  if (typeof item === 'string') {
                    try {
                      return JSON.parse(item);
                    } catch (e) {
                      return item;
                    }
                  }
                  return item;
                }));
              } else {
                resolve(responseData.data);
              }
            } else {
              reject(new Error(responseData.message || '请求失败'));
            }
          } else if (res.statusCode === 401) {
            wx.clearStorageSync();
            wx.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/index/index'
              });
            }, 1500);
            reject(new Error('登录已过期，请重新登录'));
          } else {
            reject(new Error(`网络请求失败(${res.statusCode})`));
          }
        } catch (err) {
          console.error('数据处理失败：', err);
          console.log('原始响应数据：', res.data);
          reject(new Error('数据解析失败，请稍后重试'));
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        reject(new Error('网络请求失败，请检查网络连接'));
      },
      timeout: 15000
    });
  });
};

export const uploadFile = (options) => {
  const token = wx.getStorageSync('token');
  
  if (!token) {
    wx.redirectTo({
      url: '/pages/index/index'
    });
    return Promise.reject(new Error('请先登录'));
  }

  const url = `${config.BASE_API}/api${options.url}`;

  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url,
      filePath: options.filePath,
      name: options.name || 'file',
      formData: options.formData,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (res.statusCode === 200) {
            if (data.code === 0) {
              resolve(data.data);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } else if (res.statusCode === 401) {
            wx.clearStorageSync();
            wx.redirectTo({
              url: '/pages/index/index'
            });
            reject(new Error('登录已过期，请重新登录'));
          } else {
            reject(new Error(`上传失败(${res.statusCode})`));
          }
        } catch (err) {
          console.error('数据解析失败：', err);
          console.log('原始响应数据：', res.data);
          reject(new Error('数据解析失败，请稍后重试'));
        }
      },
      fail: (err) => {
        console.error('上传失败：', err);
        reject(new Error('上传失败，请检查网络连接'));
      }
    });
  });
}; 